#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, Image
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS

def exportAsTxt(exif, filename):
    items = dict.keys(exif)
    txt = open(filename, 'w')
    # Write header.
    for item in items:
        txt.write(item + ":" + str(exif[item]) + "\n")
    txt.close()

def getExifData(filename):
    ret = {}
    image = Image.open(filename)
    info = image._getexif()
    ret["linkage"] = filename
    if info:
        #  格納されているExif情報をタグ毎に順次取り出す。
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == "ExifVersion": ret[decoded] = "%s.%s.%s.%s" %(value[0], value[1], value[2], value[3])
            elif decoded == "ExifImageWidth": ret[decoded] = int(value)
            elif decoded == "ExifImageHeight": ret[decoded] = int(value)
            elif decoded == "XResolution": ret[decoded] = float(value[0])/float(value[1])
            elif decoded == "YResolution": ret[decoded] = float(value[0])/float(value[1])
            elif decoded == "ResolutionUnit": ret[decoded] = getResolutionUnit(int(value))
            elif decoded == "ColorSpace": ret[decoded] = getColorSpace(int(value))
            elif decoded == "Make": ret[decoded] = str(value)
            elif decoded == "Model": ret[decoded] = str(value)
            elif decoded == "LightSource": ret[decoded] = getLightSource(int(value))
            elif decoded == "Flash": ret[decoded] = getFlash(int(value))
            elif decoded == "MeteringMode": ret[decoded] = getMeteringMode(int(value))
            elif decoded == "ExposureProgram": ret[decoded] = getExposureProgram(int(value))
            elif decoded == "DateTimeDigitized": ret[decoded] = str(value) 
            elif decoded == "DateTimeOriginal": ret[decoded] = str(value)
            elif decoded == "CompressedBitsPerPixel": ret[decoded] = float(value[0])/float(value[1])
            elif decoded == "FNumber": ret[decoded] = float(value[0])/float(value[1])
            elif decoded == "FocalLength": ret[decoded] = float(value[0])/float(value[1])
            elif decoded == "ISOSpeedRatings": ret[decoded] = int(value)
            elif decoded == "DateTime": ret[decoded] = str(value)
            elif decoded == "Orientation": ret[decoded] = getOrientation(value)
            elif decoded == "ExposureTime": ret[decoded] = str(value[0])+"/"+str(value[1])
            elif decoded == "MaxApertureValue": ret[decoded] = str(value[0])+"/"+str(value[1])
            elif decoded == "YCbCrPositioning": ret[decoded]= getYCbCrPositioning(int(value))
            elif decoded == "GPSInfo": ret = getGpsInfo(ret, value)
    else:
        print("There are no valid Exif Tags.")
    return ret

def _if_exist(data, key):
    if key in data:
        return(data[key])
    return None

def getLightSource(value):
    if value == 0 : return("unknown")
    elif value == 1 : return("daylight")
    elif value == 2 : return("fluorescent")
    elif value == 3 : return('tungsten ("incandescent)')
    elif value == 4 : return("flash")
    elif value == 9 : return("fine weather")
    elif value == 10 : return("cloudy")
    elif value == 11 : return("shade")
    elif value == 12 : return("daylight fluorescent")
    elif value == 13 : return("day white fluorescent")
    elif value == 14 : return("cool white fluorescent")
    elif value == 15 : return("white fluorescent")
    elif value == 16 : return("warm white fluorescent")
    elif value == 17 : return("standard light a")
    elif value == 18 : return("standard light b")
    elif value == 19 : return("standard light c")
    elif value == 20 : return("D55")
    elif value == 21 : return("D65")
    elif value == 22 : return("D75")
    elif value == 23 : return("D50")
    elif value == 24 : return("iso studio tungsten")
    elif value == 255 : return("other")
    else: return("Not Defined")
    
    return(None)

def getResolutionUnit(value):
    if value == 1 : return("None")
    elif value == 2 : return("inches")
    elif value == 3 : return("cm")
    else: return("Not Defined")
    
    return(None)

def getExposureProgram(value):
    if value == 0 : return("Not Defined")
    elif value == 1 : return("Manual")
    elif value == 2 : return("Program AE")
    elif value == 3 : return("Aperture-priority AE")
    elif value == 4 : return("Shutter speed priority AE")
    elif value == 5 : return("Creative (Slow speed)")
    elif value == 6 : return("Action (High speed)")
    elif value == 7 : return("Portrait")
    elif value == 8 : return("Landscape")
    elif value == 9 : return("Bulb")
    else: return("Not Defined")
    
    return(None)

def getColorSpace(value):
    if value == 1 : return("sRGB")
    if value == 2 : return("Adobe RGB")
    if value == 65533 : return("Wide Gamut RGB")
    if value == 65534 : return("ICC Profile")
    if value == 65535 : return("Uncalibrated")
    
    return(None)

def getFlash(value):    
    if value == 0 : return("No Flash")
    elif value == 1 : return("Fired")
    elif value == 5 : return("Fired: Return not detected")
    elif value == 7 : return("Fired: Return detected")
    elif value == 8 : return("On: Did not fire")
    elif value == 9 : return("On: Fired")
    elif value == 13 : return("On: Return not detected")
    elif value == 15 : return("On: Return detected")
    elif value == 16 : return("Off: Did not fire")
    elif value == 20 : return("Off: Did not fire: Return not detected")
    elif value == 24 : return("Auto: Did not fire")
    elif value == 25 : return("Auto: Fired")
    elif value == 29 : return("Auto: Fired: Return not detected")
    elif value == 31 : return("Auto: Fired: Return detected")
    elif value == 32 : return("No flash function")
    elif value == 48 : return("Off: No flash function")
    elif value == 65 : return("Fired: Red-eye reduction")
    elif value == 69 : return("Fired: Red-eye reduction: Return not detected")
    elif value == 71 : return("Fired: Red-eye reduction: Return detected")
    elif value == 73 : return("On: Red-eye reduction")
    elif value == 77 : return("On: Red-eye reduction: Return not detected")
    elif value == 79 : return("On: Red-eye reduction: Return detected")
    elif value == 80 : return("Off: Red-eye reduction")
    elif value == 88 : return("Auto: Did not fire: Red-eye reduction")
    elif value == 89 : return("Auto: Fired: Red-eye reduction")
    elif value == 93 : return("Auto: Fired: Red-eye reduction: Return not detected")
    elif value == 95 : return("Auto: Fired: Red-eye reduction: Return detected")
    else: return("Not Defined")
    
    return(None)

def getMeteringMode(value):
    if value == 0 : return("Unknown")
    elif value == 1 : return("Average")
    elif value == 2 : return("Center-weighted average")
    elif value == 3 : return("Spot")
    elif value == 4 : return("Multi-spot")
    elif value == 5 : return("Multi-segment")
    elif value == 6 : return("Partial")
    elif value == 255 : return("Other")
    else: return("Not Defined")
    
    return(None)

def getOrientation(value):
    if value == 1 : return("Horizontal (normal)")
    if value == 2 : return("Mirror horizontal")
    if value == 3 : return("Rotate 180")
    if value == 4 : return("Mirror vertical")
    if value == 5 : return("Mirror horizontal and rotate 270 CW")
    if value == 6 : return("Rotate 90 CW")
    if value == 7 : return("Mirror horizontal and rotate 90 CW")
    if value == 8 : return("Rotate 270 CW")
    
    return(None)

def getYCbCrPositioning(value):
    if value == 1 : return("Centered")
    if value == 2 : return("Co-sited")
    
    return(None)

def getGpsInfo(decodedDict, values):
    gpsInfo = {}
    for tag in values:
        decoded = GPSTAGS.get(tag, tag)
        if decoded == "GPSVersionID": decodedDict[decoded] = getGpsVersionID(values[tag])
        elif decoded == "GPSLatitudeRef": decodedDict[decoded] = values[tag]
        elif decoded == "GPSLongitudeRef": decodedDict[decoded] = values[tag]
        elif decoded == "GPSAltitudeRef": decodedDict[decoded] = values[tag]
        elif decoded == "GPSSpeedRef": decodedDict[decoded] = getGpsSpeedRef(values[tag])
        elif decoded == "GPSTrackRef": decodedDict[decoded] = getGpsDirection(values[tag])
        elif decoded == "GPSTimeStamp": decodedDict[decoded] = getGpsTimeStamp(values[tag])
        elif decoded == "GPSStatus": decodedDict[decoded] = getGpsStatus(values[tag])
        elif decoded == "GPSMeasureMode": decodedDict[decoded] = getGpsMeasureMode(values[tag])
        elif decoded == "GPSSpeed": decodedDict[decoded] = float(values[tag][0])/float(values[tag][1])
        elif decoded == "GPSTrack": decodedDict[decoded] = float(values[tag][0])/float(values[tag][1]) 
        elif decoded == "GPSImgDirectionRef": decodedDict[decoded] = getGpsDirection(values)
        elif decoded == "GPSImgDirection": decodedDict[decoded] = float(values[tag][0])/float(values[tag][1]) 
        elif decoded == "GPSMapDatum": decodedDict[decoded] = values[tag]
        elif decoded == 29 : decodedDict["GPSDateStamp"] = values[tag]
        elif decoded == 30 : decodedDict["GPSDifferential"] = getGpsDifferenctial(values[tag])
        else: decodedDict[decoded] = values[tag]
    
    # Extract Geographic location from Exif tags.
    lat = None; lon = None; alt = None
    
    exif_lat = _if_exist(values, 2)
    exif_lon = _if_exist(values, 4)
    alt = _if_exist(values, 6)
    
    lat_ref = _if_exist(values,1)
    lon_ref = _if_exist(values,3)
    alt_ref = _if_exist(values,5)
    
    # Get latitude and longitude.
    if exif_lat and lat_ref and exif_lon and lon_ref:
        lat = getDegree(exif_lat); 
        lon = getDegree(exif_lon)
        if lat_ref != "N" : lat = 0 - float(lat)
        if lon_ref != "E" : lon = 0 - float(lon)
        decodedDict["GPSLatitude"] = float(lat)
        decodedDict["GPSLongitude"] = float(lon)
    
    # Get Altitude.
    if alt and alt_ref:
        if alt_ref != 0 : 0 - (float(alt[0])/float(alt[1]))
        decodedDict["GPSAltitude"] = float(alt[0])/float(alt[1])
    
    # Get Dop Information.
    exif_dop = _if_exist(values, 11)
    dop_ref = _if_exist(values, 10)
    
    if exif_dop and dop_ref:
        if dop_ref == 2 : dop_label = "HDOP"
        elif dop_ref == 3 : dop_label = "PDOP"
        else: dop_label = "GPSDOP"
        value = float(exif_dop[0])/float(exif_dop[1])
        decodedDict[dop_label] = value
    return(decodedDict)
    return(None)

def getGpsVersionID(value):
    ret = ""
    v1 = str(value[0])
    v2 = str(value[1])
    v3 = str(value[2])
    v4 = str(value[3])
    ret = "%s.%s.%s.%s" % (v1, v2, v3, v4)
    return(ret)

def getGpsTimeStamp(value):
    ret = ""
    h = float(value[0][0]) / float(value[0][1])
    m = float(value[0][0]) / float(value[0][1])
    s = float(value[0][0]) / float(value[0][1])
    ret = "%02d:%02d:%02d" % (h, m, s)
    return(ret)

def getGpsStatus(value):
    if value == "A": return("Measurement is in progress")
    elif value == "V" : return("Measurement is in Interoperability")
    else: return("Not Available")

def getGpsMeasureMode(value):
    if value == 2 : return("2D")
    elif value == 3 : return("3D")
    else: return("Not Available")

def getGpsSpeedRef(value):
    if value == "K" : return("Km/h")
    elif value == "M" : return("Mile/h")
    elif value == "N" : return("Nots/h")
    else: return("Not Available")

def getGpsDirection(value):
    if value == "T" : return("True direction")
    elif value == "M" : return("Magnetic direction")
    else: return("Not Available")

def getGpsDifferenctial(value):
    if value == 0 : return("Measurement without differential correction")
    if value == 1 : return("Differential correction applied")

def getDegree(value):
    d = float(value[0][0])/float(value[0][1])
    m = float(value[1][0])/float(value[1][1])
    s = float(value[2][0])/float(value[2][1])
    ret = d + (m/60.0) + (s/3600.0)
    return(ret)

def getImgInDir(parent):
    res = []
    for child in os.listdir(parent):
        fullpath = os.path.join(parent, child)
        filename = os.path.splitext(fullpath)[0]
        extension = os.path.splitext(fullpath)[1].lower()
        if os.path.isdir(fullpath):
            getImgInDir(fullpath)
        elif extension == ".jpg" or extension == ".jpeg" or extension == ".tif" or extension ==".tiff":
            res.append(getExifData(fullpath))
            '''
            if _if_exist(res, "GPSLongitude") != None and _if_exist(res, "GPSLatitude") != None:
                print(str(res["GPSLatitude"]) + "/" + str(res["GPSLongitude"]))
            '''
    return res

def exportWithCsv(exif, output):
    # Open a file to write.
    f = open(output, 'w')
    
    # Write header columns.
    h =  '"linkage", "Orientation", "ExifVersion", "ExifImageWidth", "ExifImageHeight", "DateTimeOriginal", "DateTimeDigitized", "DateTime", "Make", "Model", "FNumber", "FocalLength", "ISOSpeedRatings", "ExposureTime", "MaxApertureValue", "Flash", "MeteringMode", "LightSource", "ExposureProgram", "ColorSpace", "YCbCrPositioning", "CompesedBitsPerPixel", "XResolution", "YResolution", "ResolutionUnit", "GPSDateStamp", "GPSTimeStamp", "GPSMeasureMode", "GPSMapDatum", "GPSDOP", "GPSStatus", "GPSLatitude", "GPSLatitudeRef", "GPSLongitude", "GPSLongitudeRef", "GPSAltitude", "GPSAltitudeRef", "GPSImgDirection", "GPSImgDirectionRef", "GPSSpeed", "GPSTrack", "GPSTrackRef", "GPSSpeedRef", "GPSDifferential"'
    f.write(h + "\n")
    for e in exif:
        s = ""
        if _if_exist(e, 'linkage') != None: s = s + str(e['linkage']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'Orientation') != None: s = s + str(e['Orientation']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'ExifVersion') != None: s = s + str(e['ExifVersion']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'ExifImageWidth') != None: s = s + str(e['ExifImageWidth']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'ExifImageHeight') != None: s = s + str(e['ExifImageHeight']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'DateTimeOriginal') != None: s = s + str(e['DateTimeOriginal']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'DateTimeDigitized') != None: s = s + str(e['DateTimeDigitized']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'DateTime') != None: s = s + str(e['DateTime']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'Make') != None: s = s + str(e['Make']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'Model') != None: s = s + str(e['Model']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'FNumber') != None: s = s + str(e['FNumber']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'FocalLength') != None: s = s + str(e['FocalLength']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'ISOSpeedRatings') != None: s = s + str(e['ISOSpeedRatings']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'ExposureTime') != None: s = s + str(e['ExposureTime']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'MaxApertureValue') != None: s = s + str(e['MaxApertureValue']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'Flash') != None: s = s + str(e['Flash']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'MeteringMode') != None: s = s + str(e['MeteringMode']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'LightSource') != None: s = s + str(e['LightSource']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'ExposureProgram') != None: s = s + str(e['ExposureProgram']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'ColorSpace') != None: s = s + str(e['ColorSpace']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'YCbCrPositioning') != None: s = s + str(e['YCbCrPositioning']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'CompesedBitsPerPixel') != None: s = s + str(e['CompesedBitsPerPixel']).strip(",").strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'XResolution') != None: s = s + str(e['XResolution']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'YResolution') != None: s = s + str(e['YResolution']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'ResolutionUnit') != None: s = s + str(e['ResolutionUnit']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSDateStamp') != None: s = s + str(e['GPSDateStamp']).strip() + str(', ')
        else: s = s + ","
        if _if_exist(e, 'GPSTimeStamp') != None: s = s + str(e['GPSTimeStamp']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSMeasureMode') != None: s = s + str(e['GPSMeasureMode']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSMapDatum') != None: s = s + str(e['GPSMapDatum']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSDOP') != None: s = s + str(e['GPSDOP']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSStatus') != None: s = s + str(e['GPSStatus']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSLatitude') != None: s = s + str(e['GPSLatitude']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSLatitudeRef') != None: s = s + str(e['GPSLatitudeRef']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSLongitude') != None: s = s + str(e['GPSLongitude']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSLongitudeRef') != None: s = s + str(e['GPSLongitudeRef']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSAltitude') != None: s = s + str(e['GPSAltitude']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSAltitudeRef') != None: s = s + str(e['GPSAltitudeRef']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSImgDirection') != None: s = s + str(e['GPSImgDirection']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSImgDirectionRef') != None: s = s + str(e['GPSImgDirectionRef']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSSpeed') != None: s = s + str(e['GPSSpeed']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSTrack') != None: s = s + str(e['GPSTrack']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSTrackRef') != None: s = s + str(e['GPSTrackRef']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSSpeedRef') != None: s = s + str(e['GPSSpeedRef']).strip() + str(', ')
        else: s = s + ", "
        if _if_exist(e, 'GPSDifferential') != None: s = s + str(e['GPSDifferential']).strip() + str(', ')
        else: s = s + ", "
        s = s.encode("UTF-8").rstrip(", ")
        f.write(s + "\n")
        f.close()

def exportWithHtml(exif, output):
    # Open a file to write.
    for e in exif:
        # Get an image file and its name from the exif information.
        img = str(e['linkage']).strip()
        name = os.path.basename(img)
        
        f = open(os.path.join(output, str(name)+".html"), 'w')
        
        # Write the HTML declaration.
        f.write("<!DOCTYPE html>")
        f.write("<html>")
        f.write("<head>")
        f.write("\t<title>%s</title>" % ("Meta data of " + str(name)))
        f.write("</head>")
        
        # Write the body block.
        f.write("<body>" + str("\n"))
        
        # Write the table block for exif metadata.
        f.write("<table>" + str("\n"))
        f.write("\t<tr><td>File Name</td><td>%s</td></tr>" % (name) + str("\n"))        
        if _if_exist(e, 'Orientation') != None:
            f.write("\t<tr><td>Orientation</td><td>%s</td></tr>" % (str(e['Orientation']).strip())) + str("\n")
        if _if_exist(e, 'ExifVersion') != None:
            f.write("\t<tr><td>ExifVersion</td><td>%s</td></tr>" % (str(e['ExifVersion']).strip())) + str("\n")
        if _if_exist(e, 'ExifImageWidth') != None:
            f.write("\t<tr><td>ExifImageWidth</td><td>%s</td></tr>" % (str(e['ExifImageWidth']).strip())) + str("\n")
        if _if_exist(e, 'ExifImageHeight') != None: 
            f.write("\t<tr><td>ExifImageHeight</td><td>%s</td></tr>" % (str(e['ExifImageHeight']).strip())) + str("\n")
        if _if_exist(e, 'DateTimeOriginal') != None: 
            f.write("\t<tr><td>DateTimeOriginal</td><td>%s</td></tr>" % (str(e['DateTimeOriginal']).strip())) + str("\n")
        if _if_exist(e, 'DateTimeDigitized') != None: 
            f.write("\t<tr><td>DateTimeDigitized</td><td>%s</td></tr>" % (str(e['DateTimeDigitized']).strip())) + str("\n")
        if _if_exist(e, 'DateTime') != None: 
            f.write("\t<tr><td>DateTime</td><td>%s</td></tr>" % (str(e['DateTime']).strip())) + str("\n")
        if _if_exist(e, 'Make') != None: 
            f.write("\t<tr><td>Make</td><td>%s</td></tr>" % (str(e['Make']).strip())) + str("\n") 
        if _if_exist(e, 'FNumber') != None: 
            f.write("\t<tr><td>FNumber</td><td>%s</td></tr>" % (str(e['FNumber']).strip())) + str("\n")
        if _if_exist(e, 'FocalLength') != None: 
            f.write("\t<tr><td>FocalLength</td><td>%s</td></tr>" % (str(e['FocalLength']).strip())) + str("\n")
        if _if_exist(e, 'ISOSpeedRatings') != None: 
            f.write("\t<tr><td>ISOSpeedRatings</td><td>%s</td></tr>" % (str(e['ISOSpeedRatings']).strip())) + str("\n")
        if _if_exist(e, 'ExposureTime') != None: 
            f.write("\t<tr><td>ExposureTime</td><td>%s</td></tr>" % (str(e['ExposureTime']).strip())) + str("\n")
        if _if_exist(e, 'MaxApertureValue') != None: 
            f.write("\t<tr><td>MaxApertureValue</td><td>%s</td></tr>" % (str(e['MaxApertureValue']).strip())) + str("\n")
        if _if_exist(e, 'Flash') != None: 
            f.write("\t<tr><td>Flash</td><td>%s</td></tr>" % (str(e['Flash']).strip())) + str("\n")
        if _if_exist(e, 'MeteringMode') != None: 
            f.write("\t<tr><td>MeteringMode</td><td>%s</td></tr>" % (str(e['MeteringMode']).strip())) + str("\n")
        if _if_exist(e, 'LightSource') != None: 
            f.write("\t<tr><td>LightSource</td><td>%s</td></tr>" % (str(e['LightSource']).strip())) + str("\n")
        if _if_exist(e, 'ExposureProgram') != None: 
            f.write("\t<tr><td>ExposureProgram</td><td>%s</td></tr>" % (str(e['ExposureProgram']).strip())) + str("\n")
        if _if_exist(e, 'ColorSpace') != None: 
            f.write("\t<tr><td>ColorSpace</td><td>%s</td></tr>" % (str(e['ColorSpace']).strip())) + str("\n")
        if _if_exist(e, 'YCbCrPositioning') != None: 
            f.write("\t<tr><td>YCbCrPositioning</td><td>%s</td></tr>" % (str(e['YCbCrPositioning']).strip())) + str("\n")
        if _if_exist(e, 'CompesedBitsPerPixel') != None: 
            f.write("\t<tr><td>CompesedBitsPerPixel</td><td>%s</td></tr>" % (str(e['CompesedBitsPerPixel']).strip(",").strip())) + str("\n")
        if _if_exist(e, 'XResolution') != None: 
            f.write("\t<tr><td>XResolution</td><td>%s</td></tr>" % (str(e['XResolution']).strip())) + str("\n")
        if _if_exist(e, 'YResolution') != None: 
            f.write("\t<tr><td>YResolution</td><td>%s</td></tr>" % (str(e['YResolution']).strip())) + str("\n")
        if _if_exist(e, 'ResolutionUnit') != None: 
            f.write("\t<tr><td>ResolutionUnit</td><td>%s</td></tr>" % (str(e['ResolutionUnit']).strip())) + str("\n")
        if _if_exist(e, 'GPSDateStamp') != None: 
            f.write("\t<tr><td>GPSDateStamp</td><td>%s</td></tr>" % (str(e['GPSDateStamp']).strip())) + str("\n")
        if _if_exist(e, 'GPSTimeStamp') != None: 
            f.write("\t<tr><td>GPSTimeStamp</td><td>%s</td></tr>" % (str(e['GPSTimeStamp']).strip())) + str("\n")
        if _if_exist(e, 'GPSMeasureMode') != None: 
            f.write("\t<tr><td>GPSMeasureMode</td><td>%s</td></tr>" % (str(e['GPSMeasureMode']).strip())) + str("\n")
        if _if_exist(e, 'GPSMapDatum') != None: 
            f.write("\t<tr><td>GPSMapDatum</td><td>%s</td></tr>" % (str(e['GPSMapDatum']).strip())) + str("\n")
        if _if_exist(e, 'GPSDOP') != None: 
            f.write("\t<tr><td>GPSDOP</td><td>%s</td></tr>" % (str(e['GPSDOP']).strip())) + str("\n")
        if _if_exist(e, 'GPSStatus') != None: 
            f.write("\t<tr><td>GPSStatus</td><td>%s</td></tr>" % (str(e['GPSStatus']).strip())) + str("\n")
        if _if_exist(e, 'GPSLatitude') != None: 
            f.write("\t<tr><td>GPSLatitude</td><td>%s</td></tr>" % (str(e['GPSLatitude']).strip())) + str("\n")
        if _if_exist(e, 'GPSLatitudeRef') != None: 
            f.write("\t<tr><td>GPSLatitudeRef</td><td>%s</td></tr>" % (str(e['GPSLatitudeRef']).strip())) + str("\n")
        if _if_exist(e, 'GPSLongitude') != None: 
            f.write("\t<tr><td>GPSLongitude</td><td>%s</td></tr>" % (str(e['GPSLongitude']).strip())) + str("\n")
        if _if_exist(e, 'GPSLongitudeRef') != None: 
            f.write("\t<tr><td>GPSLongitudeRef</td><td>%s</td></tr>" % (str(e['GPSLongitudeRef']).strip())) + str("\n")
        if _if_exist(e, 'GPSAltitude') != None: 
            f.write("\t<tr><td>GPSAltitude</td><td>%s</td></tr>" % (str(e['GPSAltitude']).strip())) + str("\n")
        if _if_exist(e, 'GPSAltitudeRef') != None: 
            f.write("\t<tr><td>GPSAltitudeRef</td><td>%s</td></tr>" % (str(e['GPSAltitudeRef']).strip())) + str("\n") + str("\n")
        if _if_exist(e, 'GPSImgDirectionRef') != None: 
            f.write("\t<tr><td>GPSImgDirectionRef</td><td>%s</td></tr>" % (str(e['GPSImgDirectionRef']).strip())) + str("\n")
        if _if_exist(e, 'GPSSpeed') != None: 
            f.write("\t<tr><td>GPSSpeed</td><td>%s</td></tr>" % (str(e['GPSSpeed']).strip())) + str("\n")
        if _if_exist(e, 'GPSTrack') != None: 
            f.write("\t<tr><td>GPSTrack</td><td>%s</td></tr>" % (str(e['GPSTrack']).strip())) + str("\n")
        if _if_exist(e, 'GPSTrackRef') != None: 
            f.write("\t<tr><td>GPSTrackRef</td><td>%s</td></tr>" % (str(e['GPSTrackRef']).strip())) + str("\n")
        if _if_exist(e, 'GPSSpeedRef') != None: 
            f.write("\t<tr><td>GPSSpeedRef</td><td>%s</td></tr>" % (str(e['GPSSpeedRef']).strip())) + str("\n")
        if _if_exist(e, 'GPSDifferential') != None: 
            f.write("\t<tr><td>GPSDifferential</td><td>%s</td></tr>" % (str(e['GPSDifferential']).strip())) + str("\n")
        f.write("</table>") + str("\n")
        f.write("</boy>") + str("\n")
        f.write("</html>") + str("\n")
        f.close()
        
if __name__ == "__main__":
    indir = ''
    output = ''
    otype = ''
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:o:t:", ["indir=", "output=", "type="])
    except getopt.GetoptError:
        print 'read.py -i <inputdir> -o <output>, -t <outputfiletype>'
        sys.exit(2)
    
    for opt, arg in opts:
        if opt == '-h':
            print 'read.py -i <inputdir> -o <output>, -t <outputfiletype>'
            sys.exit()
        elif opt in ("-i", "--indir"):
            indir = arg
        elif opt in ("-o", "--output"):
            outdir = arg
        elif opt in ("-t", "--type"):
            otype = arg.lower()
    
    exif = getImgInDir(indir)
    
    if otype == "csv":
        exportWithCsv(exif, output)
    elif otype == "html":
        exportWithHtml(exif, output)